const url = "https://up-z2.qiniup.com/";
const cache = new Map();//已上传的文件不再上传
function make(file, token) {
    return new Promise((resolve, reject) => {
        const key = new Date().getTime() + Math.ceil(Math.random() * 80000 + 10000) + "";
        if (cache.has(file)) {
            resolve(cache.get(file))
            return
        }

        console.log("上传中..." + file)
        wx.uploadFile({
            url: url,
            filePath: file,
            name: 'file',
            formData: {
                key,
                token,
            },
            success: res => {
                cache.set(file, key)
                resolve(key);
            },
            fail: res => {

                console.log(res);
                reject();
            }
        })
    });
}

function clearCache() {
    cache.clear()
}

function upload(files, token) {
    let arr = [];
    if (typeof files === "string") {
        arr.push(files);
    } else if (files instanceof Array) {
        arr = arr.concat(files);
    } else {
        return Promise.resolve("");
    }
    if (arr.length == 0) {
        return Promise.resolve("");
    }
    let ps = arr.map(o => {
        return make(o, token);
    });
    return Promise.all(ps)
}

module.exports = { upload, clearCache };